package ink.xiaobaibai.serviceOxy.free.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.bo.DeviceMqttBo;
import ink.xiaobaibai.entity.DeviceLog;
import ink.xiaobaibai.entity.FreeOxygenDevice;
import ink.xiaobaibai.entity.FreeOzoneDevice;
import ink.xiaobaibai.service.IDeviceLogService;
import ink.xiaobaibai.service.IFreeOxygenDeviceService;
import ink.xiaobaibai.service.IFreeOzoneDeviceService;
import ink.xiaobaibai.serviceOxy.IMqttService;
import ink.xiaobaibai.serviceOxy.free.IDeviceFreeControlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-08-08
 **/

@Service
public class DeviceFreeControlServiceImpl implements IDeviceFreeControlService {

    @Autowired
    private IFreeOzoneDeviceService freeOzoneDeviceService;

    @Autowired
    private IFreeOxygenDeviceService freeOxygenDeviceService;

    @Autowired
    private IDeviceLogService deviceLogService;

    @Autowired
    private IMqttService mqttService;

    @Override
    public void open(Integer deviceId, String roomNumber, Integer seconds) {
        FreeOzoneDevice freeOzoneDevice = this.freeOzoneDeviceService.getById(deviceId);
        FreeOxygenDevice freeOxygenDevice = this.freeOxygenDeviceService.getById(freeOzoneDevice.getOxygenId());
        this.mqttService.openDevice(freeOzoneDevice.getDeviceCode(), new DeviceMqttBo(freeOzoneDevice.getDeviceCode(), true, freeOzoneDevice.getDelayedTime(), freeOzoneDevice.getFanTime(), freeOzoneDevice.getValveTime(), seconds, roomNumber));
        this.mqttService.openDevice(freeOxygenDevice.getDeviceCode(), new DeviceMqttBo(freeOxygenDevice.getDeviceCode(), true, freeOxygenDevice.getDelayedTime(), freeOxygenDevice.getFanTime(), freeOxygenDevice.getValveTime(), seconds, roomNumber));
        this.deviceLogService.save(new DeviceLog(deviceId, freeOzoneDevice.getDeviceCode(), seconds));
    }

    @Override
    public void close(Integer deviceId, String roomNumber) {
        QueryWrapper<FreeOzoneDevice> q1 = new QueryWrapper<>();
        q1.select("device_code", "oxygen_id");
        q1.eq("id", deviceId);
        FreeOzoneDevice freeOzoneDevice = this.freeOzoneDeviceService.getOne(q1);
        QueryWrapper<FreeOxygenDevice> q2 = new QueryWrapper<>();
        q2.select("device_code");
        q2.eq("id", freeOzoneDevice.getOxygenId());
        FreeOxygenDevice freeOxygenDevice = this.freeOxygenDeviceService.getOne(q2);
        this.mqttService.closeDevice(freeOzoneDevice.getDeviceCode(), roomNumber);
        this.mqttService.closeDevice(freeOxygenDevice.getDeviceCode(), roomNumber);
        this.deviceLogService.save(new DeviceLog(deviceId, freeOzoneDevice.getDeviceCode(), -1));
    }

}
